//
//  WBNewFeatureView.swift
//  CFZWeiBo
//
//  Created by Cedric Zheng on 27/11/2016.
//  Copyright © 2016 Cedric Zheng. All rights reserved.
//

import UIKit

class WBNewFeatureView: UIView {
    
    lazy var newFeatureScrollView: UIScrollView = {
       let scrollView = UIScrollView()
        scrollView.bounces = false
        scrollView.delegate = self
        scrollView.isPagingEnabled = true
        scrollView.showsHorizontalScrollIndicator = false
        scrollView.showsVerticalScrollIndicator = false
        scrollView.frame = self.bounds
        return scrollView
    }()
    
    lazy var pageControl: UIPageControl = {
       let pageControl = UIPageControl()
        pageControl.currentPageIndicatorTintColor = globalColor
        pageControl.pageIndicatorTintColor = UIColor.softColor(withHue: .blueHue)
        pageControl.numberOfPages = 4
        pageControl.currentPage = 0
        return pageControl
    }()

    override init(frame: CGRect) {
        super.init(frame: mainScreenBounds)
        
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

}

// MARK: - Setup methods
extension WBNewFeatureView {
    
    func setupUI() {
        backgroundColor = UIColor.clear
        
        addSubview(newFeatureScrollView)
        addSubview(pageControl)
        
        for i in 1...4 {
            let imageView = UIImageView(imageName: "new_feature_\(i)")
            imageView.frame = newFeatureScrollView.frame.offsetBy(dx: screenWidth * CGFloat(i-1), dy: 0)
            newFeatureScrollView.addSubview(imageView)
        }
        
        newFeatureScrollView.contentSize = CGSize(width: screenWidth*5, height: screenHeight)
        
        pageControl.snp.makeConstraints { (make) in
            make.centerX.equalToSuperview()
            make.bottom.equalToSuperview().offset(-screenHeight*0.1)
        }
    }
    
}

// MARK: - Delegates
extension WBNewFeatureView: UIScrollViewDelegate {
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        let offset = scrollView.contentOffset.x
        let currentPage = Int(offset/screenWidth + 0.5)
        pageControl.currentPage = currentPage
        
        //Makes pageControl moves with the image at the last page
        let screenWidthX3 = screenWidth * 3
        if offset > screenWidthX3 {
            pageControl.snp.updateConstraints({ (make) in
                make.centerX.equalToSuperview().offset(-offset + screenWidthX3)
            })
        }
        
        if offset >= screenWidth * 4 {
            removeFromSuperview()
        }
    }
    
}
